package org.ourguy.mymoviesandshows;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ourguy.mymoviesandshows.datamodel.Episode;
import org.ourguy.mymoviesandshows.datamodel.ITitle;
import org.ourguy.mymoviesandshows.datamodel.Season;
import org.ourguy.mymoviesandshows.datamodel.Series;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;

public class ShowSeasonsActivity extends ExpandableListActivity {
    
    private Series show;
    private DataAccessManager menager;
    private DownloadSeasonsInfo info;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        menager = DataAccessManager.getInstance(this);
        
        show = (Series)menager.getTitle(getIntent().getStringExtra("show"));
        
        info = new DownloadSeasonsInfo(this);
        info.execute();
    }
    
    @SuppressWarnings("unchecked")
	@Override
    public boolean onChildClick(ExpandableListView parent, View v,
    		int groupPosition, int childPosition, long id) {
    	Intent intent = new Intent(this, EpisodeActivity.class);
    	intent.putExtra("show", show.getApiId());
    	String seasonNumber = ((Map<String, String>)getExpandableListAdapter().getGroup(0)).get("seasons");
    	intent.putExtra("season", groupPosition + ((seasonNumber == "Specials")? 0:1));
    	intent.putExtra("episode", childPosition + 1);
		this.startActivity(intent);
    	return true;
    }
    
    @Override
    protected void onStop() {
    	info.cancel(true);
    	super.onStop();
    }
    
    class DownloadSeasonsInfo extends AsyncTask<Void, Void, Boolean> {
    	private ArrayList<Season> seasons = null;
    	private ExpandableListActivity activity;
    	private ProgressDialog dialog;
    	private Context context;
    	
    	public DownloadSeasonsInfo(ExpandableListActivity activity) {
    		this.activity = activity;
    		this.context = activity;
    		dialog = new ProgressDialog(context);
		}
    	
    	@Override
    	protected void onPreExecute() {
    		this.dialog.setMessage("Please wait until the list is downloaded");
    		this.dialog.setIndeterminate(true);
    		this.dialog.show();
    	}
    	
    	@Override
    	protected Boolean doInBackground(Void... unused) 
    	{
    		int count=0;
    		if(show.isInFavorites()&&count<10)
    		{
    			while(show.getSeasonList() == null)
    			{
    				try{Thread.sleep(1000);}catch (Exception e) {}
    				count++;
    			}
    		}
			if (show.getSeasonList() == null) {
				try {
					seasons = menager.getSeasonsForTitle(show);
				} catch (Throwable ignored) {
					return false;
				}
				show.setSeasons(seasons);
			}else
			{
				seasons = show.getSeasonList();
			}
            
            return true;
	    }
    	@Override
    	protected void onProgressUpdate(Void...unused) {	
    	}
    	@Override
    	protected void onPostExecute(final Boolean success) {
    		if(success) {
	    		List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
	            List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();
	            for (int i = 0; i < seasons.size(); i++) {
	            	Season season = seasons.get(i);
	            	if(season != null)
	            	{	
	    	            Map<String, String> curGroupMap = new HashMap<String, String>();
	    	            groupData.add(curGroupMap);
	    	            if(season.getNumber() == 0)
	    	            	curGroupMap.put("seasons", "Specials");
	    	            else
	    	            	curGroupMap.put("seasons", "Season " + season.getNumber());
	    	            curGroupMap.put( "episodes", "Episodes:" + season.numEpisodes());
	    	            
	    	            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
	    	            for (int j = 0; j < season.numEpisodes(); j++) {
	    	            	try{
	    		            	Episode episode = season.getEpisodeAt(j);
	    		            	if(episode != null)
	    		            	{
	    		            		Map<String, String> curChildMap = new HashMap<String, String>();
	    		            		children.add(curChildMap);
	    		            		curChildMap.put("episode", episode.getNumber() + ": " + episode.getTitle());
	    		            		curChildMap.put("aired", "Aired: " + episode.getFirstAired().toGMTString());
	    		            	}
	    	            	}catch (Exception e) {
	    					}
	    	            }
	    	            childData.add(children);
	                }
	            }
	            
	            ExpandableListAdapter mAdapter = new SimpleExpandableListAdapter(
	                    activity,
	                    groupData,
	                    android.R.layout.simple_expandable_list_item_1,
	                    new String[] { "seasons", "episodes" },
	                    new int[] { android.R.id.text1, android.R.id.text2 },
	                    childData,
	                    android.R.layout.simple_expandable_list_item_2,
	                    new String[] { "episode", "aired" },
	                    new int[] { android.R.id.text1, android.R.id.text2 }
	                    );
	            	activity.setListAdapter(mAdapter);
    		}
    		else {
				Toast.makeText(context, "Error loading seasons...try again.",
						Toast.LENGTH_LONG);
			}
    		if (dialog.isShowing())
				dialog.hide();
    	}
    }

}
